package cn.ham.ms.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author jianghan
 * @date 2018-10-24 14:28
 */
public class DynamicDataSourceHolder {

    private static Logger logger = LoggerFactory.getLogger(DynamicDataSourceHolder.class);
    private static final ThreadLocal<DbType> contextHolder = new ThreadLocal<>();
    public enum DbType {
        master("master", "主库"),
        slave("slave", "从库");
        private String type;
        private String name;

        DbType(String type, String name) {
            this.type = type;
            this.name = name;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    public static void setDbType(DbType dbType) {
        logger.info("set data source.");
        if(dbType == null){
            contextHolder.set(DbType.master);
        }else {
            contextHolder.set(dbType);
        }
    }

    public static String getDbType() {
        DbType dbType = contextHolder.get();
        return  dbType == null ? DbType.master.getType() : dbType.getType();
    }

    public static void clearDbType() {
        contextHolder.remove();
    }
}
